var db = wx.cloud.database()

import {
	areaList
} from '../../miniprogram_npm/@vant/area-data/area-data';

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		swiperList: ['/images/bg.png'],
		code: '',
		username: '',
		usernumber: '',
		userlocal: '',
		shengshiqu: '',
		show: false,
		isHasAppleData: false,
		areaList
	},
	getData() {
		db.collection("demouser").get({
			success: res => {
				console.log(res);
			}
		})
	},
	showPopup() {
		this.setData({
			show: true
		})
	},
	onClose() {
		this.setData({
			show: false
		})
	},
	queding(e) {
		let area = e.detail.values
		this.setData({
			show: false,
			shengshiqu: area[0].name + area[1].name + area[2].name,
		})
	},
	quxiao() {
		this.setData({
			show: false
		})
	},
	filterSpace(e) {
		let value = e.detail.value.replace(/\s/g, '');
		this.setData({
			code: value
		});
	},

	matchData: async function () {
		let that = this
		const db = wx.cloud.database()
		const collection = db.collection('uuidCollection')
		const matchValue = this.data.code
		try {
			const result = await collection.where({
				uuid: matchValue
			}).get()
			const time = new Date().getTime()

			if (result.data.length > 0) {
				if (result.data[0].timestamp > time) {
					if (result.data[0].uuid == this.data.code) {
						console.log('匹配成功:', result.data)
						const id = result.data[0]._id;
						db.collection('uuidCollection')
							.doc(id)
							.remove({
								success: function (res) {
									that.addData()
									console.log('删除成功');
								},
								fail: function (err) {
									console.error('删除失败:', err);
								}
							});
					}
				} else {
					wx.showToast({
						title: "兑换码已失效",
						icon: 'none',
					})
				}
			} else {
				wx.showToast({
					title: "兑换码无效",
					icon: 'none',
				})
			}

		} catch (err) {
			console.error('查询失败:', err)
		}
	},
	submitData() {
		let reg = /^1[3-9]\d{9}$/;
		if (!this.data.code) {
			wx.showToast({
				title: "请输入兑换码",
				icon: 'none',
			})
		} else if (!this.data.username) {
			wx.showToast({
				title: "请输入姓名",
				icon: 'none',
			})
		} else if (!this.data.usernumber) {
			wx.showToast({
				title: "请输入联系电话",
				icon: 'none',
			})
		} else if (!this.data.shengshiqu) {
			wx.showToast({
				title: "请点击选择地址",
				icon: 'none',
			})
		} else if (!this.data.userlocal) {
			wx.showToast({
				title: "请输入详细地址",
				icon: 'none',
			})
		} else if (!reg.test(this.data.usernumber)) {
			wx.showToast({
				title: "手机格式不对",
				icon: 'none',
			})
		} else {
			if (!this.data.isHasAppleData) {
				this.matchData()
			} else {
				wx.showToast({
					title: "一个账号只可兑换一次哦",
					icon: 'none',
				})
			}
		}
	},
	getNowTime() {
		let currentDate = new Date();
		let year = currentDate.getFullYear();
		let month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
		let day = currentDate.getDate().toString().padStart(2, '0');
		let hours = currentDate.getHours().toString().padStart(2, '0');
		let minutes = currentDate.getMinutes().toString().padStart(2, '0');
		let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
		return formattedDate;
	},
	addData() {
		wx.showLoading({
			title: '加载中',
			mask: true,
		})
		db.collection('demouser').add({
			data: {
				code: this.data.code,
				username: this.data.username,
				usernumber: this.data.usernumber,
				userlocal: this.data.userlocal,
				shengshiqu: this.data.shengshiqu,
				creatTime: this.getNowTime(),
				switchChecked: false,
				isEdit: false
			}
		}).then(res => {
			console.log(res);
			wx.hideLoading()
			wx.showToast({
				title: "兑换成功",
				icon: 'none',
			})
			this.setData({
				code: "",
				username: "",
				usernumber: "",
				userlocal: "",
				shengshiqu: "",
				switchChecked: false
			})
		})
	},
	shouquan() {
		wx.requestSubscribeMessage({
			tmplIds: ['7_lHddYrgpZCqjvhXCP4D5xX-Sc2iugjxXzex2-Somg'],
			success(res) {
				console.log('授权成功', res);
			},
			fail(err) {
				console.log('授权失败', err);
			}
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.cloud.callFunction({
			name: 'getOpenId', // 调用的云函数名称
			complete: res => {
				db.collection('demouser').where({
					_openid: res.result.openid
				}).get().then(res => {
					if (res.data.length > 0) {
						console.log('已兑换过');
						this.setData({
							isHasAppleData: true
						})
					} else {
						console.log('还未兑换过');
					}
				})
			}
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})